package com.monitoringfloty.androidclient;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class SettingsSingleton implements SettingsInvoker {

	private static volatile SettingsSingleton instance = null;
	private static final String PREFERENCES_NAME = "myPreferences";
	private Context cntx;
	private SharedPreferences preferences;
	private SharedPreferences.Editor editor;
	private ArrayList<SettingsListener> listeners;

	public static SettingsSingleton getInstance() {
        if (instance == null) {
            synchronized (positionUpdater.class) {
                if (instance == null) {
                    instance = new SettingsSingleton();
                }
            }
        }
        return instance;
    }
	
    private SettingsSingleton() {
    	if(cntx!=null)
    		preferences = cntx.getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
    	listeners = new ArrayList<SettingsListener>();
    }
    
    public void setContext(Context settedContext) {
    	cntx=settedContext;
    	if(cntx!=null) {
    		preferences = cntx.getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
    		editor = preferences.edit();
    	}
    		
    }
    
    
    public String getString(String key, String defa) {
    	return preferences.getString(key, defa);
    }
    
    public void putString(String key, String value) {
    	editor.putString(key, value);
    	editor.commit();
    	notifyListeners();
    }
    
    public boolean getBool(String key, boolean defa) {
    	return preferences.getBoolean(key, defa);
    }
    
    public void putBool(String key, boolean value) {
    	editor.putBoolean(key, value);
    	editor.commit();
    	notifyListeners();
    }

	@Override
	public void addListener(SettingsListener o) {
		// TODO Auto-generated method stub
		listeners.add(o);
	}

	@Override
	public void removeListener(SettingsListener o) {
		// TODO Auto-generated method stub
		int index = listeners.indexOf(o);
		listeners.remove(index);
	}

	@Override
	public void notifyListeners() {
		// TODO Auto-generated method stub
		for(SettingsListener o : listeners){
			o.onSettingsUpdate(null);
			}
	}
    
    
    
    

}
